#include "ct.h"

/////////////////////////////// Port Declarations //////////////////////////////
WORDREADCSP_ab32_dataT WORDREADCSP_ab32_data;
handlesT handles;

/////////////////////////////// Diagnostic level ///////////////////////////////
Uns32 diagnosticLevel;

/////////////////////////// Diagnostic level callback //////////////////////////
static void setDiagLevel(Uns32 new) {
    diagnosticLevel = new;
}

///////////////////////////// MMR Generic callbacks ////////////////////////////
static PPM_VIEW_CB(view32) {  *(Uns32*)data = *(Uns32*)user; }

/////////////////////////////////// Net Ports //////////////////////////////////
static void installNetPorts(void) {
	handles.intp = ppmOpenNetPort("intp");
	handles.readNextTime = ppmOpenNetPort("readNextTime");
	handles.readNextValue = ppmOpenNetPort("readNextValue");
}

//////////////////////////// Memory mapped registers ///////////////////////////
static void installRegisters(void) {

    ppmCreateRegister("wordData",
        "data",
        handles.WORDREADCSP,
        0,
        4,
        regRd32,
        0,
        view32,
        &(WORDREADCSP_ab32_data.wordData.value),
        True
    );
}

//////////////////////////////// Bus Slave Ports ///////////////////////////////
static void installSlavePorts(void) {
    handles.WORDREADCSP = ppmCreateSlaveBusPort("WORDREADCSP", 32); // 9 is the size of extent to be exposed, needs to be the difference between icmConnectPSEBus highAddress and lowAddress?

}

////////////////////////////////// Constructor /////////////////////////////////
PPM_CONSTRUCTOR_CB(periphConstructor) {
	installSlavePorts();
	installRegisters();
	installNetPorts();
	nextValue = 0;
}

///////////////////////////////////// Main /////////////////////////////////////
int main(int argc, char *argv[]) {
    diagnosticLevel = 0;
    bhmInstallDiagCB(setDiagLevel);
    constructor();

	ppmInstallNetCallback(handles.readNextValue, wroteNewValue, (void*)0);
	
	nextTime = ppmReadNet(handles.readNextTime);
	nextValue = ppmReadNet(handles.readNextValue);
	
	while(nextValue != 2) {
		bhmWaitDelay(nextTime); // stops thread for nextTime microseconds
		if(nextValue == 1) { // prooves if we need to interrupt
			ppmWriteNet(handles.intp, 1); // stops thread for a given timeperiod
			LOG("Set interrupt, after %d microseconds\n", nextTime);
		}
	}
	
    destructor();
    return 0;
}

